<template>
  <el-dialog
    v-model="dialogVisible"
    title="提交维修工单"
    :width="isMobile ? '90%' : '600px'"
    :before-close="handleClose"
    :modal="false"
    :lock-scroll="false"
    :draggable="true"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :append-to-body="true"
    class="custom-dialog"
  >
    <div class="dialog-header">
      <h2 class="dialog-title">维修工单申请</h2>
      <p class="dialog-subtitle">请填写设备信息，我们将尽快安排处理</p>
    </div>

    <el-form 
  ref="formRef" 
  :model="workorderForm" 
  :rules="workorderRules" 
  class="workorder-form"
  label-width="0"
  :validate-on-rule-change="false"
>
      <!-- 设备编号 -->
      <el-form-item prop="deviceModel">
        <div class="form-field">
          <el-icon class="field-icon"><Cpu class="icon" /></el-icon>
          <el-input
            v-model="workorderForm.deviceModel"
            placeholder="请输入设备编号（设备背面标签）"
            :maxlength="30"
            :prefix-icon="null"
            class="form-control "
          />
        </div>
      </el-form-item>

      <!-- 故障描述 -->
      <el-form-item prop="faultDescription">
        <div class="form-field">
          <el-icon class="field-icon"><Warning class="icon" /></el-icon>
          <el-input
            v-model="workorderForm.faultDescription"
            type="textarea"
            placeholder="请描述设备故障现象（500字以内）"
            class="form-control "
          />
        </div>
      </el-form-item>

      <!-- 联系方式 -->
      <el-form-item prop="contactPhone">
        <div class="form-field">
          <el-icon class="field-icon"><Phone class="icon" /></el-icon>
          <el-input
            v-model="workorderForm.contactPhone"
            placeholder="请输入有效手机号码"
            :prefix-icon="null"
            class="form-control"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-actions">
        <el-button 
          type="text" 
          @click="closeDialog"
          class="cancel-btn"
        >
          取消申请
        </el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
          :disabled="loading"
          class="submit-btn"
        >
          提交工单
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue';
import service from '~/axios';
import { toast } from '~/composables/util';
import { getToken } from '~/composables/auth';
import { useAuthStore } from '~/stores/authStore';
import { ElForm, ElFormItem, ElInput, ElButton, ElIcon, ElDialog } from 'element-plus';
import { Cpu, Warning, Phone } from '@element-plus/icons-vue';

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

// 定义emits
const emit = defineEmits(['update:visible', 'success']);

// 本地状态同步prop
const dialogVisible = ref(props.visible);

// 监听prop变化同步到本地状态
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
});

// 监听本地状态变化通知父组件更新
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

const authStore = useAuthStore();
const loading = ref(false);
const workorderForm = ref({
  deviceName: '',
  deviceModel: '',
  faultDescription: '',
  contactPhone: '',
  address: ''
});
const closeDialog=()=>{
  dialogVisible.value = false;
  workorderForm.value.deviceModel="";
  workorderForm.value.deviceName="";
  workorderForm.value.faultDescription="";
  workorderForm.value.contactPhone="";
  workorderForm.value.address="";
  //将规则重置
  formRef.value.clearValidate();
}
// 表单实例引用
const formRef = ref(null);

const workorderRules = ref({
  deviceModel: [
    { required: true, message: '请输入设备编号', trigger: 'blur' },
    { min: 2, max: 30, message: '设备编号长度在 2 到 30 个字符之间', trigger: 'blur' }
  ],
  faultDescription: [
    { required: true, message: '请描述故障情况', trigger: 'blur' },
    { min: 5, max: 500, message: '故障描述长度在 5 到 500 个字符之间', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
});

const handleSubmit = async () => {
  if (!getToken()) {
    toast('请先登录', 'warning');
    dialogVisible.value = false;
    return;
  }
  try {
    await formRef.value.validate();
    loading.value = true;
    const userId = authStore.userInfo.id;
const description = workorderForm.value.faultDescription
const contactInfo = workorderForm.value.contactPhone
const deviceCode = workorderForm.value.deviceModel

const url = `/api/user/commit?user_id=${userId}&description=${description}&contact_info=${contactInfo}&device_code=${deviceCode}`;

await service.post(url);

    toast('工单提交成功');
    emit('success');
    emit('update:visible', false);
    // 重置表单
Object.assign(workorderForm.value, {
  deviceName: '',
  deviceModel: '',
  faultDescription: '',
  contactPhone: '',
  address: ''
});

// 重置表单验证状态
formRef.value.resetFields();
  } catch (error) {
    toast('工单提交失败，请稍后重试', 'error');
    console.error('提交失败:', error);
  } finally {
    loading.value = false;
  }
};

const handleClose = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.custom-dialog {
  --dialog-bg: #f8f9fa;
  --primary-color: #2c7be5;
  --success-color: #10b981;
  --error-color: #ef4444;
  --border-radius: 12px;
  --box-shadow: 0 8px 20px rgba(44, 123, 229, 0.1);
}

.el-dialog {
  background: var(--dialog-bg) !important;
  border-radius: var(--border-radius) !important;
  box-shadow: var(--box-shadow) !important;
  margin: 20px auto !important;
}

.dialog-header {
  padding: 24px 20px 16px;
  background: linear-gradient(135deg, #2c7be5 0%, #1d58b3 100%);
  border-top-left-radius: var(--border-radius);
  border-top-right-radius: var(--border-radius);
  color: white;
}

.dialog-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px;
}

.dialog-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.5;
}

.workorder-form {
  padding: 24px 32px;
  background: white;
  border-radius: var(--border-radius);
  margin: -20px auto 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.form-field {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 24px;
  padding-top: 8px;
}

.field-icon {
  color: var(--primary-color);
  font-size: 20px;
}

.form-control {
  flex: 1;
  min-height: 56px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  width: 400px;
  transition: all 0.3s ease;
  background: #fff;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.04);
}

.form-control:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(44, 123, 229, 0.2);
  outline: none;
}



.custom-textarea {
  height: 140px;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  gap: 16px;
  padding: 24px;
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

.cancel-btn {
  padding: 12px 24px;
  color: var(--primary-color);
  border: 1px solid var(--primary-color);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: var(--primary-color);
  color: white;
}

.submit-btn {
  padding: 12px 32px;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(44, 123, 229, 0.3);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .custom-dialog {
    width: 90% !important;
  }
  
  .dialog-header {
    padding: 20px;
  }
  
  .form-field {
    flex-direction: column;
    gap: 8px;
  }
  
  .field-icon {
    margin: 0 0 8px 0;
  }
}
</style>